package com.tz.ebusiness.entity;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import lombok.Data;

@Data
public class Cart implements Serializable{

	private static final long serialVersionUID = 2538594814136841772L;
	private Map<Long, OrderItem> items = new HashMap<>();
	private double total;
	private int count = 0;

	// 添加到购物车
	public void addCart(OrderItem item) {
		OrderItem oi = items.get(item.getItemId());
		if (oi == null) {
			items.put(item.getItemId(), item);
			this.total += item.getTotal();
			this.count++;
		} else {
			oi.setCount(oi.getCount() + item.getCount());
			oi.setTotal(oi.getTotal() + (oi.getPrice()-oi.getDiscount()) * item.getCount());
			this.total += oi.getPrice() * item.getCount();
		}
	}

	// 清空购物车
	public void clear() {
		items.clear();
		this.total = 0.0;
		this.count = 0;
	}

	// 修改数量
	public void modifyCount(Long goodsId, int count) {
		OrderItem item = items.get(goodsId);
		if (item != null) {
			item.setTotal(item.getTotal() + (count - item.getCount()) * item.getPrice());
			this.total += (count - item.getCount()) * item.getPrice();
			item.setCount(count);
		}
	}

	// 删除某个条目
	public void delete(Long goodsId) {
		this.total -= items.get(goodsId).getTotal();
		Iterator<Map.Entry<Long, OrderItem>> iter = items.entrySet().iterator();
		while (iter.hasNext()) {
			if (iter.next().getKey() == goodsId) {
				iter.remove();
			}
		}
		this.count--;
	}

	//获取购物车的商品详情
	public OrderItem findById(Long goodsId) {
		OrderItem item = items.get(goodsId);
		return item;
	}
}
